package cn.sell.filter;

import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

/**
 * @Author: Limi
 * @Contact : qq(2393839633),Email(13924223985@163.com)
 * @Description: TODO:
 * @Date: 2020/4/3 14:41
 * @Version: 1.0
 **/
@Log4j2
@Order(-99)
@WebFilter(urlPatterns = "/admin/rest/*")
public class AuthorizeFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        log.info("=================== 过滤器开始工作 ===================");
        HttpServletRequest req = ((HttpServletRequest) request);
        request.setAttribute("requestId", start);
        log.info("id:" + start + "-url: " + req.getRequestURL().toString());

        //获得所有头的名字
        Enumeration<String> em = req.getHeaderNames();
        while (em.hasMoreElements()) {
            String key = em.nextElement();
            String value = req.getHeader(key);
            log.debug("请求头：key:{},value:{}", key, value);
        }
        Map<String, String[]> map = request.getParameterMap();
        for (String parameter : map.keySet()) {
            log.debug("请求参数为：{}:{}", parameter, map.get(parameter).toString());
        }
        // 防止流读取一次后就没有了, 所以需要将流继续写出去
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        RequestBodyReaderWrapper bodyReaderWrapper = new RequestBodyReaderWrapper(httpServletRequest);
        String reqStr = HttpHelper.getReqStr(bodyReaderWrapper);
        log.debug("请求体：\r\n{}", reqStr);

        //获取请求中的流，将取出来的字符串，再次转换成流，然后把它放入到新request对象中。
        // 在chain.doFiler方法中传递新的request对象
        if (bodyReaderWrapper == null) {
            log.debug("bodyReaderWrapper == null");
            filterChain.doFilter(request, response);
        } else {
            log.debug("bodyReaderWrapper != null");
            filterChain.doFilter(bodyReaderWrapper, response);
        }
        log.info("id:" + start + "-总耗时 : " + (System.currentTimeMillis() - start) / 1000f + " 秒");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
